package com.xinyue.game.client.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
/**
 * 
 * @ClassName: GameRemoteClient 
 * @Description: socket连接，负责连接服务器，向服务器发送消息
 * @author: wgs
 * @date: 2018年12月3日 下午2:16:36
 */
public class GameRemoteClient {
    private Logger logger = LoggerFactory.getLogger(GameRemoteClient.class);
    private String ip = "127.0.0.1";
    private int port = 8809;

    private Socket socket;

    public void connect() {
        try {
            socket = new Socket();
            SocketAddress endpoint = new InetSocketAddress(ip, port);
            socket.connect(endpoint, 60000);
        } catch (IOException e) {
            logger.error("连接失败服务器：{}：{}", ip, port, e);
        }
    }

    public void close() {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            socket = null;
        }
    }

    public String sendMessage(JSONObject message, int messageId) {
        if (socket == null) {
            logger.error("服务器未连接");
            return null;
        }
        try {
            OutputStream out = socket.getOutputStream();
            byte[] msg = CodecFactory.encode(message, messageId).array();
            out.write(msg);
            out.flush();

            InputStream in = socket.getInputStream();
            byte[] readBytes = new byte[1024];
            ByteBuf bytebuf = Unpooled.buffer(1024 * 1024);
            int len = 0;
            while ((len = in.read(readBytes)) != -1) {
                bytebuf.writeBytes(readBytes, 0, len);
                int total = bytebuf.readableBytes();
                bytebuf.markReaderIndex();
                // 接收完一个包退出
                int count = bytebuf.readShort();
                if (total == count) {
                    bytebuf.resetReaderIndex();
                    break;
                }
                bytebuf.resetReaderIndex();
            }
            String result = CodecFactory.decode(bytebuf);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}
